package com.beemans.common.utils

import android.os.Handler
import android.os.Looper
import java.util.*
import java.util.concurrent.ScheduledExecutorService
import java.util.concurrent.ScheduledThreadPoolExecutor
import java.util.concurrent.ThreadFactory
import java.util.concurrent.TimeUnit
import kotlin.concurrent.timerTask

/**
 * @author tiamosu
 * @date 2021/3/13
 *
 * 描述：定时轮训服务
 */
class CountDownService {
    private var handler: Handler? = null
    private var timerTask: TimerTask? = null
    private var executorService: ScheduledExecutorService? = null
    var isCountDowning = false

    fun startTask(
        runnable: () -> Unit,
        initialDelay: Long = 0,
        period: Long = 1000,
        unit: TimeUnit = TimeUnit.MILLISECONDS
    ) {
        if (isCountDowning) return
        isCountDowning = true

        if (handler == null) {
            handler = Handler(Looper.getMainLooper()) {
                runnable.invoke()
                true
            }
        }
        if (timerTask == null) {
            timerTask = timerTask {
                handler?.sendEmptyMessage(TIMER_MSG_CODE)
            }
        }
        if (executorService == null) {
            executorService = ScheduledThreadPoolExecutor(1, ThreadFactory { Thread(it) })
        }

        timerTask?.let {
            executorService?.scheduleAtFixedRate(it, initialDelay, period, unit)
        }
    }

    fun stopTask() {
        isCountDowning = false

        if (timerTask != null) {
            timerTask!!.cancel()
            timerTask = null
        }
        if (executorService != null) {
            executorService!!.shutdownNow()
            executorService = null
        }
        if (handler != null) {
            handler!!.removeMessages(TIMER_MSG_CODE)
            handler = null
        }
    }

    companion object {
        const val TIMER_MSG_CODE = 1
    }
}